var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var debug = require('debug')('app4');
var superagent = require('superagent');
var cheerio = require('cheerio');
var qs = require('querystring');
var eventproxy = require('eventproxy');
var hbs = require('hbs');
var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'html');
app.engine('html',hbs.__express);//设置模版引擎
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



//设置中间件，运行Html上Javascript脚本进行跨域访问
app.use(function(req,res,next){
  res.setHeader('Access-Control-Allow-Origin','*');
  res.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
  res.setHeader('Access-Control-Allow-Methods','GET,POST,PUT,DELETE');
  next();
});

app.use('/', routes);
//app.use('/users', users);

app.get('/api/plan',function(req,res){
  var provicne = req.query.province;
  var year = req.query.year;
  if(typeof(provicne) ==='undefined' || typeof(year) === 'undefined'){
    res.end("参数错误");
    return false;
  }
  var getURL = 'http://admission.shmtu.edu.cn/plan/'+year+'/'+qs.escape(provicne);
  superagent.get(getURL)
            .end(function(err,data){
              if(err){
                console.log(err);return err;
              }
              var $ = cheerio.load(data.text);
              table = $(".table>tbody").html();
              res.end(table);
            });
});



app.get('/api/score',function(req,res){
  var provicne = req.query.province;
  var year = req.query.year;
  if(typeof(provicne) ==='undefined' || typeof(year) === 'undefined'){
    res.end("参数错误");
    return false;
  }
  var getURL = 'http://admission.shmtu.edu.cn/score/'+year+'/'+qs.escape(provicne);
  superagent.get(getURL)
            .end(function(err,data){
              if(err){
                console.log(err);return err;
              }
              var $ = cheerio.load(data.text);
              table = $(".table>tbody").html();
              res.end(table);
            });
});


app.get('/api',function(req,res){
  res.end("hello world");

});

app.use('/api',function(req,res){
  console.log(req.body);
  res.end("你的ID是:"+req.body.id+",返回的结果为：dog");
});

app.use('/login',function(req,res){
  console.log(req.body);
  res.json({"msg":"this is a msg"});
});


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


//module.exports = app;
app.set('port', process.env.PORT || 5051);

var server = app.listen(app.get('port'), function() {
  console.log('this server is running at port:' + server.address().port);
});